<template>
    <div class="chatroomMembers">
        <div class='moduleHead'>
            <span class="center">
                <router-link :to="{ name: 'chat' }">
                    <span class="back"></span>
            </router-link>
            <span> {{language.chatroomMembers_title}} </span>
            </span>
        </div>
        <div class="body">
            <dl class="editBox">
                <dd>
                    <label>{{language.chatroomMembers_status}}</label>
                    <select @change="changeMyStatus" class="selectA" v-model="fliterObj.myStatus">
                        <option v-for="item in statusRender.select" :value="item.value">{{item.label}}</option>
                    </select>
                    <div class="arrow"></div>
                </dd>
                <dd>
                    <label>{{language.chatroomMembers_show}}</label>
                    <select @change="resetFliterOnlineValue('show')" class="selectA" v-model="fliterObj.show">
                        <option v-for="item in genderRender.select" :value="item.value">{{item.label}}</option>
                    </select>
                    <div class="arrow"></div>
                </dd>
                <dd>
                    <label>{{language.chatroomMembers_sort}}</label>
                    <select @change="resetFliterOnlineValue('sort')" class="selectA" v-model="fliterObj.sort">
                        <option v-for="item in sortRender.select" :value="item.value">{{item.label}}</option>
                    </select>
                    <div class="arrow"></div>
                </dd>
            </dl>
            <div class="title">{{language.chatroomMembers_online}}</div>
            <ul class="userlist">
                <li v-for="item in onlineUsersItems" @click="gotoUserProfile(item.usr_id)" :key="item.usr_id">
                    <div class="avatar" :class="getGenderBgClass(item.gender)">
                        <lazyImg :src="filterGenderImg(item.icon)"></lazyImg>
                        <div v-if="parseInt(item.photoCount) > 0" class="photoNum"><span></span>{{ item.photoCount }}</div>
                        <div v-if="parseInt(item.photoCount) > 0" class="bbg"></div>
                    </div>
                    <div class="info">
                        <div class="name">
                            <span v-if="parseInt(item.isGuest) == 0" class="ico_gold"></span>
                            <span class="username">{{ item.username }} <span class="invisible" v-if="item.my_status"> ({{language.chatroomMembers_invisibleLabel}})</span></span>
                        </div>
                        <div v-if="!item.profile_hidden" class="text location">
                            {{ item.baseInfo }}
                        </div>
                        <div class="text" v-if="item.profile_hidden">{{language.unify_hideProfile}}</div>
                        <div class="text" v-else>{{ item.headline }}</div>
                    </div>
                </li>
                <loading :props="{show:loadUsersBool}"></loading>
            </ul>
        </div>
        <publicDialog :props="dialogData"></publicDialog>
    </div>
</template>
<script>
import chatPartMixin from '../common/chatPartMixin'
import * as API from '../api'
import lazyImg from './LazyImg'
import publicDialog from './PublicDialog'
import loading from './Loading'
import globalMixin from '../common/globalMixin'

let specialAccount = ['livesupport'],
    cacheSpecialAccount = [];

export default {
    name: 'chatroomMembers',

    mixins: [chatPartMixin, globalMixin],

    components: {
        lazyImg,
        publicDialog,
        loading
    },

    data: function() {
        return {
            dialogData: {},
            allOnlineUser: [],
            loadUsersBool: true,
            fliterObj: {
                myStatus: 'online',
                show: '',
                sort: 'username',
                invisibleUser: [],
            },
        }
    },

    activated: function() {
        this.dialogData = {};
        this.fliterObj.show = Unit.getObjSessionStorage('ms_userOnlineObj') != null ? Unit.getObjSessionStorage('ms_userOnlineObj').show : '';
        this.fliterObj.sort = Unit.getObjSessionStorage('ms_userOnlineObj') != null ? Unit.getObjSessionStorage('ms_userOnlineObj').sort : 'username';
        this.fliterObj.invisibleUser = Unit.getObjSessionStorage('ms_invisible_user') || [];
    },

    computed: {

        genderRender() {
            let obj = {
                select: Unit.getObjLocalStorage('ms_gender')
            };
            obj.select.unshift({
                'label': this.language.chatroomMembers_all,
                'value': ''
            });
            return obj;
        },

        statusRender() {
            let obj = {
                select: [{
                        label: this.language.chatroomMembers_onlineLabel,
                        value: 'online'
                    },
                    {
                        label: parseInt(this.userInfo.status.isGuest) == 1 ? this.language.chatroomMembers_invisibleLabelGuest : this.language.chatroomMembers_invisibleLabel,
                        value: 'invisible'
                    },
                ]
            };
            return obj;
        },

        sortRender() {
            let obj = {
                select: [{
                        label: this.language.unify_username,
                        value: 'username'
                    },
                    {
                        label: this.language.unify_age,
                        value: 'age'
                    },
                    {
                        label: this.language.unify_state,
                        value: 'state'
                    },
                    {
                        label: this.language.unify_country,
                        value: 'country'
                    },
                    {
                        label: this.language.chatroomMembers_photoFirst,
                        value: 'photofirst'
                    },
                ]
            };
            return obj;
        },

        onlineUsersItems: function() {
            let newArr = [],
                tthis = this;
            for (let i in tthis.allOnlineUser) {
                newArr.push(tthis.formatUserInfo(tthis.getUserObj(tthis.allOnlineUser[i]).userInfo));
            }
            newArr = tthis.fliterOnlineUser(newArr, this.fliterObj);
            return newArr;
        },
    },

    created() {

        let tthis = this;
        this.$root.$on('chat_reset', function() {
            tthis.clearUsers();
        });

        this.OnlineUserHandler = {
            proccess: function(obj, args) {
                console.log('OnlineUserHandler', args, obj);
                tthis.loadOnlineUsersOK(args.list);
            }
        };

        this.StatusChangeHandler = {
            proccess: function(obj, args) {
                console.log("StatusChangeHandler:", args);
                tthis.setUserStatus(args);
            }
        };

        this.PreferenceHandler = {
            proccess: function(obj, args) {
                console.log('PreferenceHandler', args);
                tthis.initMyStatus(args.online_status);
            }
        };

        this.PresenceHandler = {
            proccess: function(obj, args) {
                console.log("PresenceHandler: ", args);
                tthis.peopleAction(args);
            }
        };

    },

    methods: {
        componentConnectOK() {
            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ONLINE_USERS, this.OnlineUserHandler);
            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.USER_STATUS, this.StatusChangeHandler);
            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.PREFERENCE, this.PreferenceHandler);
            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.PRESENCE, this.PresenceHandler);
            this.loadOnlineUsers();
        },

        fliterOnlineUser(userArr, fliterObj) {
            let tthis = this;
            tthis.fliterSpecialAccount(userArr);
            userArr = this.foreachBlock(userArr);
            userArr = this.showOnlineUser(fliterObj.show, userArr);
            userArr = this.sortOnlineUser(fliterObj.sort, userArr);
            userArr = this.delInvisibleUser(fliterObj.invisibleUser, userArr);
            userArr = this.orderUserList(userArr);
            userArr = this.addSpecialAccount(fliterObj.invisibleUser, userArr);
            if (userArr.length > 0) {
                tthis.loadUsersBool = false;
            };
            return userArr
        },

        fliterSpecialAccount(userArr) {
            var arr = [];
            for (var i in userArr) {
                if (Unit.inArray(userArr[i].username.toLowerCase(), specialAccount) > -1) {
                    cacheSpecialAccount.push(userArr[i]);
                } else {
                    arr.push(userArr[i]);
                }
            }
            return arr;
        },

        filterUsersCache(users) {
            var obj = {},
                tthis = this,
                filterUser = [];
            for (var i in users) {
                if (!tthis.checkIsCache(users[i], 'username')) {
                    filterUser.push(users[i]);
                }
            }
            return filterUser.join(',');
        },

        getCacheUserInfoByUsername(username) {
            let usersInfo = Unit.getObjSessionStorage('usersInfo') || {};
            for (var i in usersInfo) {
                if (usersInfo.hasOwnProperty(i)) {
                    if (usersInfo[i].userInfo.account.username.toLowerCase() == username.toLowerCase()) {
                        return usersInfo[i].userInfo;
                    }
                };
            }
            return {};
        },

        foreachShowUser(userArr, key, value) {
            var arr = [];
            for (var i in userArr) {
                if (userArr[i][key] == value) {
                    arr.push(userArr[i]);
                }
            }
            return arr;
        },

        showOnlineUser(show, userArr) {
            if (show !== '') {
                userArr = this.foreachShowUser(userArr, 'gender', show);
            }
            return userArr;
        },

        sortOnlineUser(type, userArr) {
            let tthis = this;
            switch (type) {
                case 'username':
                    userArr = tthis.sortAZ(userArr, 'name');
                    break;
                case 'age':
                    userArr = tthis.sortNum(userArr, 'age', function(a, b) {
                        return a - b;
                    });
                    break;
                case 'state':
                    userArr = tthis.sortAZ(userArr, 'state');
                    break;
                case 'photofirst':
                    userArr = tthis.sortNum(userArr, 'photoCount', function(a, b) {
                        return b - a;
                    });
                    break;
                case 'country':
                    userArr = tthis.sortAZ(userArr, 'country');
                    break;
                default:
                    userArr = tthis.sortAZ(userArr, 'name');
                    break;
            }
            return userArr;
        },

        sortAZ(arr, key) {
            var newArr = [],
                arrAZ = _.uniq(_.map(arr, key).sort());
            for (var i in arrAZ) {
                for (var j in arr) {
                    if (arr[j][key] == arrAZ[i]) {
                        newArr.push(arr[j]);
                    }
                }
            }
            return newArr;
        },

        sortNum(arr, key, func) {
            var newArr = [],
                arrSort = _.uniq(_.map(_.map(arr, key).sort(func), function(num) {
                    return parseInt(num);
                }));
            for (var i in arrSort) {
                for (var j in arr) {
                    if (parseInt(arr[j][key]) == arrSort[i]) {
                        newArr.push(arr[j]);
                    }
                }
            }
            return newArr;
        },

        delInvisibleUser(invisibleUser, userArr) {
            for (let i in invisibleUser) {
                for (let j in userArr) {
                    if (invisibleUser[i] == userArr[j].usr_id && invisibleUser[i] !== this.userInfo.account.usr_id) {
                        userArr.splice(j, 1);
                    } else if (invisibleUser[i] == userArr[j].usr_id && invisibleUser[i] == this.userInfo.account.usr_id) {
                        userArr[j].my_status = true;
                    } else if (Unit.inArray(userArr[j].usr_id, invisibleUser) == -1 && userArr[j].usr_id == this.userInfo.account.usr_id) {
                        userArr[j].my_status = false;
                    }
                }
            }
            return userArr;
        },

        orderUserList(userArr) {
            var arr = [],
                arrA = [],
                arrB = [],
                arrC = [],
                arrD = [];
            for (var i in userArr) {
                if (userArr[i].usr_id == this.userInfo.account.usr_id) {
                    arrA.push(userArr[i]);
                } else if (userArr[i].order && parseInt(userArr[i].order) == 1) {
                    arrB.push(userArr[i]);
                } else if (userArr[i].order && parseInt(userArr[i].order) == 2) {
                    arrC.push(userArr[i]);
                } else {
                    arrD.push(userArr[i]);
                }
            }
            arr = arrA.concat(arrB, arrC, arrD);
            return arr;
        },

        addSpecialAccount(invisibleUser, userArr) {
            if (userArr.length > 0) {
                if (userArr[0].usr_id == this.userInfo.account.usr_id) {
                    for (let i in cacheSpecialAccount) {
                        if (cacheSpecialAccount[i].usr_id == userArr[0].usr_id) {
                            cacheSpecialAccount.splice(i, 1);
                            break;
                        }
                    }
                    cacheSpecialAccount.unshift(userArr[0]);
                    userArr.splice(0, 1);
                }
            }
            userArr = cacheSpecialAccount.concat(userArr);
            return userArr;
        },

        clearUsers() {
            this.allOnlineUser = [];
            this.loadUsersBool = true;
            this.fliterObj.myStatus = 'online';
            this.fliterObj.invisibleUser = [];
            Unit.setSessionStorage('ms_invisible_user', '[]');
        },

        loadOnlineUsers() {
            this.clearUsers();
            MiniIM.Action.loadOnlineUserList();
            MiniIM.Action.loadPreference('online_status');
        },

        loadOnlineUsersOK(users) {
            this.getOnlineUsersInfo(users, 'username');
        },

        getCacheUserIds(users, type) {
            let tthis = this,
                ids = [];
            if (type = 'username') {
                for (let i in users) {
                    if (tthis.checkIsCache(users[i], 'username')) {
                        ids.push(tthis.getCacheUserInfoByUsername(users[i]).account.usr_id);
                    }
                }
            } else {
                for (let i in users) {
                    if (tthis.checkIsCache(users[i])) {
                        ids.push(users[i]);
                    }
                }
            }
            return ids;
        },

        addCacheOnlineUser(users) {
            for (let i in users) {
                if (Unit.inArray(users[i], this.allOnlineUser) == -1) {
                    this.allOnlineUser.push(users[i]);
                }
            };
        },

        delCacheOnlineUser(ids) {
            for (let i in ids) {
                if (Unit.inArray(ids[i], this.allOnlineUser) > -1) {
                    this.allOnlineUser.splice(Unit.inArray(ids[i], this.allOnlineUser), 1);
                }
            };
        },

        getOnlineUsersInfo(users, type, callback) {
            let tthis = this;
            if (type == 'username') {
                tthis.addCacheOnlineUser(tthis.getCacheUserIds(users, 'username'));
                let filterUsers = tthis.filterUsersCache(users);
                if (filterUsers.length > 0) {
                    API.users_profile({
                        data: { users: filterUsers },
                        success: function(response) {
                            if (response.result == 1) {
                                tthis.adapterUsersData(response.data);
                                for (let i in response.data) {
                                    if (response.data.hasOwnProperty(i)) {
                                        tthis.addCacheOnlineUser([response.data[i].usr_id]);
                                    };
                                };
                                if (callback) {
                                    callback(response);
                                };
                            }
                        }
                    })
                }
            } else {
                tthis.addCacheOnlineUser(tthis.getCacheUserIds(users));
                tthis.getUsersInfo(users, function(response) {
                    for (let i in response.data) {
                        if (response.data.hasOwnProperty(i)) {
                            tthis.addCacheOnlineUser([response.data[i].usr_id]);
                        };
                    };
                    if (callback) {
                        callback(response);
                    };
                });
            }
            return;
        },

        resetFliterOnlineValue(type, val) {
            let tthis = this;
            if (type == 'invisibleUser') {
                Unit.setSessionStorage('ms_invisible_user', JSON.stringify(val));
                tthis.fliterObj.invisibleUser = val;
            } else {
                let obj = {
                    sort: this.fliterObj.sort,
                    show: this.fliterObj.show

                };
                Unit.setSessionStorage('ms_userOnlineObj', JSON.stringify(obj));
            }
        },

        setStatus(roomName, value) {
            MiniIM.Action.setStatus(roomName, value);
            MiniIM.Action.savePreference('online_status', value);
        },

        changeMyStatus(e) {
            let val = e.target.value,
                tthis = this;
            if (parseInt(tthis.userInfo.status.isGuest) == 1 && val == 'invisible') {
                tthis.fliterObj.myStatus = 'online';
                val = 'online';
                tthis.setStatus(tthis.userInfo.account.username.toLowerCase(), val);
                tthis.dialogData = {
                    position: 'middle',
                    type: 'upgrade',
                    content: {
                        info: tthis.language.chatroomMembers_upgradeTip,
                    }
                };
                return;
            }
            this.setStatus(this.userInfo.account.username.toLowerCase(), val);
        },

        initMyStatus(val) {
            let tthis = this;
            if (parseInt(tthis.userInfo.status.isGuest) == 1 && val == 'invisible') {
                tthis.fliterObj.myStatus = 'online';
                tthis.setStatus(tthis.userInfo.account.username.toLowerCase(), tthis.fliterObj.myStatus);
            } else {
                if (val != null) {
                    tthis.fliterObj.myStatus = (val != 'invisible' && val != 'online') ? 'online' : val;
                } else {
                    tthis.fliterObj.myStatus = 'online';
                }
                tthis.setUserStatus({
                    status: tthis.fliterObj.myStatus,
                    fromUser: tthis.userInfo.account.username.toLowerCase()
                });
            };
        },

        setUserStatus(obj) {
            let tthis = this,
                invisibleUser = Unit.getObjSessionStorage('ms_invisible_user');;
            if (invisibleUser == null) {
                invisibleUser = [];
            };
            let setInvisibleCache = function(userId, status) {
                    if (status.toLowerCase() == 'invisible' && Unit.inArray(userId, invisibleUser) == -1) {
                        invisibleUser.push(userId);
                    } else if (status.toLowerCase() == 'online' && Unit.inArray(userId, invisibleUser) != -1) {
                        invisibleUser.splice(Unit.inArray(userId, invisibleUser), 1);
                    };
                    tthis.resetFliterOnlineValue('invisibleUser', invisibleUser);
                },
                getUserId = function(response) {
                    setInvisibleCache(response.data[obj.fromUser].usr_id, obj.status);
                };
            if (tthis.checkIsCache(obj.fromUser, 'username')) {
                setInvisibleCache(tthis.getCacheUserInfoByUsername(obj.fromUser).account.usr_id, obj.status);
            } else {
                tthis.getOnlineUsersInfo([obj.fromUser], 'username', getUserId)
            }

        },

        peopleAction(obj) {
            let tthis = this,
                setType = 'add',
                hasCache = tthis.checkIsCache(obj.usr_id);
            if (obj.type == 'join') {
                if (hasCache) {
                    tthis.addCacheOnlineUser([obj.usr_id]);
                } else {
                    tthis.getOnlineUsersInfo([obj.usr_id], 'userid', function(response) {
                        tthis.addCacheOnlineUser([obj.usr_id]);
                    });
                }
            } else if (obj.type == 'leave') {
                tthis.delCacheOnlineUser([obj.usr_id]);
            }
        },

        getUserIcon(userInfo) {

            let icon = '',
                arr = userInfo.pictures;

            if (arr && arr[0] && arr[0].icon) {
                icon = arr[0].icon;
            }

            icon = this.getAvatar(userInfo.account.gender, icon);

            return icon;
        },

        formatUserInfo(userInfo) {
            let data = {};
            data.username = userInfo.account.username;
            data.usr_id = userInfo.account.usr_id;
            data.icon = this.getUserIcon(userInfo);
            data.photoCount = userInfo.photoCount;
            data.baseInfo = this.formatUserLocation({
                age: userInfo.account.age,
                city: userInfo.account.city,
                state: userInfo.account.state_name,
                country: userInfo.account.country_name,
            });
            data.gender = userInfo.account.gender;
            data.headline = userInfo.about.headline;
            data.isBlocked = userInfo.status.isBlocked;
            data.isGuest = userInfo.status.isGuest;
            data.profile_hidden = parseInt(userInfo.profile_hidden) == 1 ? true : false;
            if (userInfo.order) {
                data.order = userInfo.order;
            }
            return data;
        },

        checkIsCache(user, type) {
            let usersInfo = Unit.getObjSessionStorage('usersInfo') || {};
            for (let i in usersInfo) {
                if (usersInfo.hasOwnProperty(i)) {
                    let cacheUser = type == 'username' ? usersInfo[i].userInfo.account.username.toLowerCase() : i
                    if (cacheUser == user.toLowerCase()) {
                        return true;
                    }
                };
            }
            return false;
        },
    },

}

</script>
<style scoped>
.chatroomMembers {
    padding-top: 44px;
}

.chatroomMembers .title {
    background-color: #f6f6f6;
    color: #000;
    padding: 10px 15px;
    font-size: 14px;
}

.chatroomMembers .editBox {
    margin: 0;
}

.chatroomMembers .editBox dt {
    padding: 0 10px;
    background-color: #f6f6f6;
    color: #000;
    font-size: 16px;
    height: 20px;
    line-height: 40px;
}

.chatroomMembers .editBox dd {
    border-bottom: 1px dashed #dcdfe3;
    padding: 10px 15px;
    min-height: 20px;
    position: relative;
    text-align: left;
}

.chatroomMembers .editBox dd .arrow {
    position: absolute;
    right: 22px;
    top: 13px;
}

.chatroomMembers .editBox dd .arrow:before {
    border: 7px solid transparent;
    border-left: 6px solid #fff;
    width: 0;
    height: 0;
    position: absolute;
    top: 0;
    right: -13px;
    content: '';
    right: -14px;
    border-left-color: #c7c7cc;
}

.chatroomMembers .editBox dd .arrow:after {
    border: 7px solid transparent;
    border-left: 6px solid #fff;
    width: 0;
    height: 0;
    position: absolute;
    top: 0;
    right: -13px;
    content: '';
}

.chatroomMembers .editBox dd:last-child {
    border-bottom: 0;
}

.chatroomMembers .editBox label {
    font-size: 14px;
    color: #333;
    line-height: 20px;
    min-height: 20px;
    display: block;
}

.chatroomMembers .editBox select.selectA {
    position: absolute;
    top: 0;
    right: 20px;
    padding: 11px 0;
    color: #777;
    font-size: 14px;
    background: #fff;
    width: 60%;
}

.chatroomMembers .userlist li {
    width: 100%;
    min-height: 100px;
    position: relative;
    overflow: hidden;
    border-bottom: 1px dotted #d9d9d9;
}

.chatroomMembers .userlist li:last-child {
    border-bottom: 0;
}

.chatroomMembers .userlist .avatar {
    position: absolute;
    width: 70px;
    height: 70px;
    border-radius: 35px;
    overflow: hidden;
    left: 15px;
    top: 15px;
    background: url(../assets/default_avatar.png) no-repeat;
    background-size: 70px 70px;
    -webkit-mask-image: -webkit-radial-gradient(circle, white, black);
}

.chatroomMembers .userlist .avatar .bbg {
    content: '';
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 100%;
    border-radius: 100%;
    overflow: hidden;
    left: 0;
    top: 0;
    background: url(../assets/userlist_bbg.png) bottom center no-repeat;
}

.chatroomMembers .userlist .avatar .photoNum {
    height: 15px;
    line-height: 17px;
    position: absolute;
    z-index: 2;
    left: 0;
    right: 0;
    bottom: 5px;
    font-size: 12px;
    font-weight: bold;
    text-align: center;
    color: #fff;
}

.chatroomMembers .userlist .avatar .photoNum span {
    background: url(../assets/ico_photo.png) 0 1px no-repeat;
    background-size: 13px auto;
    padding: 0 0 0 15px;
}

.chatroomMembers .userlist .info {
    margin: 0 15px 0 105px;
    overflow: hidden;
}

.chatroomMembers .userlist .name {
    margin: 13px 0 0 0;
    padding: 0 0 0 0;
    position: relative;
    overflow: hidden;
    min-height: 28px;
    line-height: 28px;
    font-size: 15px;
}

.chatroomMembers .userlist .invisible {
    color: #999;
}

.chatroomMembers .ico_gold {
    background: url(../assets/ico_gold.png) center no-repeat;
    background-size: auto 17px;
    padding: 2px 0 2px 17px;
    margin-right: 5px;
}

.chatroomMembers .userlist .text {
    font-size: 13px;
    line-height: 25px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    color: #a3a4a6;
}

</style>
